package com.loop.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

/**
 * @author zhangxiaolu
 * @since 2023-09-15 22:42
 */
public class NettyByteBuf02 {

    public static void main(String[] args) {
        // 创建ByteBuf对象 (内容，字符集)
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello,netty", CharsetUtil.UTF_8);

        // 使用相关的Api
        if (byteBuf.hasArray()) {
            byte[] content = byteBuf.array();
            // 将content转换为字符串
            System.out.println(new String(content, CharsetUtil.UTF_8));// 编码统一
            System.out.println("byteBuf = " + byteBuf);
            System.out.println("byteBuf = " + byteBuf.arrayOffset()); // 0
            System.out.println("byteBuf = " + byteBuf.readerIndex()); // 0
            System.out.println("byteBuf = " + byteBuf.writerIndex()); // 11
            System.out.println("byteBuf = " + byteBuf.capacity()); // 33
            System.out.println("byteBuf = " + byteBuf.readableBytes()); // 可读字节数 11 随读取减少


            System.out.println("byteBuf = " + byteBuf.maxCapacity()); //2147483647
            System.out.println("byteBuf = " + byteBuf.isDirect()); // false
            System.out.println("byteBuf = " + byteBuf.order()); // BIG_ENDIAN
            System.out.println("byteBuf = " + byteBuf.nioBuffer()); // java.nio.HeapByteBuffer[pos=0 lim=11 cap=11]

            // 使用for循环取出各个字节
            for (int i = 0; i < byteBuf.readableBytes(); i++) {
                System.out.println((char) byteBuf.getByte(i));
            }

            System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8));// 读取范围的字节
        }

    }
}
